package org.softmed.action.tree;

import java.util.Map;

import org.softmed.action.Action;

public class NodeNavigator {



	public void setAction(String name, Action action, Node root) {
		getActionContainerNode(name,root).setAction(action);
	}

	public ActionContainerNode getActionContainerNode(String name, Node root) {
		if (name == null)
			throw new RuntimeException("No name given to search for action: "
					+ name);

		Map<String, Node> children = ((ParentNode) root).getChildren();

		int index = -1;
		if ((index = name.indexOf('.')) > 0) {
			String cname = name.substring(0, index);
			Node acn = children.get(cname);
			if (acn instanceof ParentNode)
				return getActionContainerNode(name.substring(index + 1), acn);

			throw new RuntimeException("There is no Parent Node named : "
					+ cname + " for action id " + name);

		} else {
			Node acn = children.get(name);
			if (acn instanceof ActionContainerNode)
				return ((ActionContainerNode) acn);

			throw new RuntimeException("There is no Action named : " + name);
		}
	}
	
	public Action getAction(String name, Node root) throws Throwable {

		return getActionContainerNode(name,root).getAction();
	}

}
